package com.dailyblue.java;

import lombok.SneakyThrows;

import java.io.*;

// 字节的输出
public class DemoD {

    @SneakyThrows
    private static void a() {
        String str = "Hello,world!";
        byte[] desc = str.getBytes();
        byte[] src = null;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        baos.write(desc, 0, 4);
        src = baos.toByteArray();
        String result = new String(src);
        System.out.println(result);
        baos.close();
    }

    @SneakyThrows
    private static void b() {
        // 设置输出的本地文件，可以不存在（会自动创建）
        File file = new File("/Users/dailyblue/a/b.txt");
        // 创建输出流对象 重载的第二个参数就是设置覆盖还是追加
        OutputStream out = new FileOutputStream(file, true);
        // 输出
        String str = "\naaaaa！";
        out.write(str.getBytes());
        // 关闭
        out.close();
    }

    // 一道机试题:文件复制操作
    @SneakyThrows
    private static void c() {
        File src = new File("/Users/dailyblue/a/b.txt");
        File desc = new File("/Users/dailyblue/a/c.txt");
        byte[] bytes = new byte[10];
        InputStream in = new FileInputStream(src);
        OutputStream out = new FileOutputStream(desc);
        int len;
        while (true) {
            len = in.read(bytes);
            if (len == -1) {
                in.close();
                out.close();
                return;
            }
            out.write(bytes, 0, len);
        }
    }

    // 1.图片复制，将一张图片剪切到另一个地方
    @SneakyThrows
    private static void d() {
        File src = new File("/Users/dailyblue/a/a/1.png");
        File desc = new File("/Users/dailyblue/a/b", src.getName());
        InputStream in = new FileInputStream(src);
        OutputStream out = new FileOutputStream(desc);
        long start = System.currentTimeMillis();
        byte[] bytes = new byte[100];
        int len;
        while ((len = in.read(bytes)) != -1) {
            out.write(bytes, 0, len);
        }
        long end = System.currentTimeMillis();
        long time = end - start;
        in.close();
        out.close();
        System.out.println("花费了" + time + "毫秒！");
        src.deleteOnExit();
    }

    // 2.文件树遍历，遍历D盘（或者某个文件夹），良好的缩进
    private static void e(File file, int index) {
        String fileName = file.getName();
        for (int i = 0; i < index; i++) {
            System.out.print("\t");
        }
        System.out.println(fileName);
        boolean b = file.isDirectory();
        if (b) {
            File[] child = file.listFiles();
            for (File f : child) {
                int m = index + 1;
                e(f, m);
            }
        }
    }

    public static void main(String[] args) {
        File file = new File("/Users/dailyblue/workspace/java/IdeaProjects");
        e(file, 0);
    }
}
